﻿using PlutoStudio.EntityFramework.Configuration;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace PlutoStudio.EntityFramework
{
    [Export]
    public class DefaultContext : Primitives.ContextBase
    {
        static DefaultContext()
        {
            if (ConfigurationManager.Migration?.Enabled??false)
            {
                Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultContext, ReportingDbMigrationsConfiguration>());
            }
            else
            {
                Database.SetInitializer<DefaultContext>(null);
            }
        }
        public DefaultContext()
           : base( "ConnectionString")
        {;
                this.Database.Log = l => TraceHelper.Helper.TraceInformation(l.Replace(System.Environment.NewLine,$"{System.Environment.NewLine}        "));
            
        }

        [ImportMany]
        protected override IEnumerable<IEntityMapper> EntityMappers { get; set; }

    }

    internal sealed class ReportingDbMigrationsConfiguration : DbMigrationsConfiguration<DefaultContext>
    {
        public ReportingDbMigrationsConfiguration()
        {
            
            AutomaticMigrationsEnabled = ConfigurationManager.Migration.Enabled;//任何Model Class的修改將會直接更新DB
            AutomaticMigrationDataLossAllowed = ConfigurationManager.Migration.CanLossData;
        }
    }
}
